// import { ref } from 'vue'
import { createStore } from 'vuex'
import { Constant } from '@/utils'

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

// 检测所有的 state 并把 `initState()` 中的属性重置
function resetState (state, moduleState) {
  const mState = state[moduleState]
  if (mState.initState && typeof mState.initState === 'function') {
    const initState = mState.initState()
    for (const key in initState) {
      mState[key] = initState[key]
    }
  }
}

export default createStore({
  state: {
  },
  actions: {
    resetStates ({ commit }, payLoad) {
      commit('resetStates', payLoad)
    }
  },
  mutations: {
    resetStates (state, payLoad) {
      for (const moduleState in state) {
        resetState(state, moduleState)
      }
    }
  },
  modules,
  strict: Constant.IS_DEV
})
